package cn.com.surker.weight.service.impl;

import cn.com.surker.base.system.entity.SysStorage;
import cn.com.surker.base.system.vo.SysStorageVo;
import cn.com.surker.common.AESCoder;
import cn.com.surker.common.Constant;
import cn.com.surker.common.MessageCenterException;
import cn.com.surker.database.JDBCTemplateCache;
import cn.com.surker.enums.material.MaterialStoreTypeEnum;
import cn.com.surker.enums.system.DataBaseEnum;
import cn.com.surker.enums.weight.DoorStatusEnum;
import cn.com.surker.enums.weight.OperationStatusEnum;
import cn.com.surker.enums.weight.StorageLogTypeEnum;
import cn.com.surker.system.dao.DataSourceInfoDao;
import cn.com.surker.system.entity.DataSourceInfo;
import cn.com.surker.util.DateUtil;
import cn.com.surker.util.StringUtils;
import cn.com.surker.weight.dao.WeightOrderDao;
import cn.com.surker.weight.dao.WeightStorageLogDao;
import cn.com.surker.weight.dto.WeightStorageInfoDto;
import cn.com.surker.weight.entity.WeightOrder;
import cn.com.surker.weight.entity.WeightStorageInfo;
import cn.com.surker.weight.dao.WeightStorageInfoDao;
import cn.com.surker.weight.entity.WeightStorageLog;
import cn.com.surker.weight.service.WeightStorageInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import cn.com.surker.spring.RestResultDto;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
* <p>
    * 过磅仓位状态 服务实现类
    * </p>
*
* @author admin
* @since 2025-05-12
*/
@Service
public class WeightStorageInfoServiceImpl extends ServiceImpl<WeightStorageInfoDao, WeightStorageInfo> implements WeightStorageInfoService {

    @Resource
    private WeightStorageInfoDao storageInfoDao;
    @Resource
    private WeightOrderDao weightOrderDao;
    @Resource
    private WeightStorageLogDao storageLogDao;
    @Resource
    private DataSourceInfoDao dsDao;

    /**
     * 分页查询仓位信息
     * @param dto
     * @param offset
     * @param limit
     * @return
     */
    public IPage findByPage(WeightStorageInfoDto dto, Integer offset, Integer limit) {
        if (StringUtils.isNull(offset))
            offset = 0;
        if (StringUtils.isNull(limit))
            limit = 15;
        PageHelper.offsetPage(offset, limit);
        QueryWrapper<WeightStorageInfo> query = new QueryWrapper<>();
        query.eq("status", 0);
        if (!StringUtils.isNull(dto.getOrgId()))
            query.eq("org_id", dto.getOrgId());
        if (!StringUtils.isNull(dto.getDoorStatus()))
            query.eq("door_status", dto.getDoorStatus());
        if (!StringUtils.isNull(dto.getSearchVal()))
            query.and(orderWrapper -> orderWrapper.like("storage", dto.getSearchVal()).or()
                    .like("material", dto.getSearchVal()).or().like("remark", dto.getSearchVal()));
        query.orderByDesc("operation_status", "door_status", "update_time");
        IPage<WeightStorageInfo> iPage = storageInfoDao.selectPage(new Page<>((offset + limit) /limit, limit), query);
        /**分页插件**/
        if (!StringUtils.isNull(iPage.getRecords())) {
            PageInfo pageInfo = new PageInfo(iPage.getRecords());
            if (!StringUtils.isNull(pageInfo.getTotal()))
                iPage.setTotal(pageInfo.getTotal());
        }
        return iPage;
    }

    /**
     * 更新仓位信息
     * @param storageInfoDto
     * @return
     */
    @CacheEvict(value = "storageInfo", allEntries = true)
    public RestResultDto updateStatus(WeightStorageInfoDto storageInfoDto) {
        if (storageInfoDto == null || StringUtils.isNull(storageInfoDto.getId()))
            throw new MessageCenterException("更新阀门状态参数异常");
        WeightStorageInfo storageInfo = storageInfoDao.selectById(storageInfoDto.getId());
        if (storageInfo == null || storageInfo.getStatus() == 1)
            throw new MessageCenterException("仓位不存在或已被禁用");
        if (storageInfoDto.getDoorStatus() == DoorStatusEnum.GB.getCode()) {
            if (storageInfoDto.getLogType() != StorageLogTypeEnum.XTGF.getCode())
                throw new MessageCenterException("阀门状态与日志状态不匹配");
            storageInfo.setOrderId("");
        }
        if (storageInfoDto.getDoorStatus() == DoorStatusEnum.KQ.getCode()) {
            if (storageInfoDto.getLogType() != StorageLogTypeEnum.XTKF.getCode())
                throw new MessageCenterException("阀门状态与日志状态不匹配");
        }
        if (storageInfo == null || storageInfo.getStatus().intValue() == 1)
            throw new MessageCenterException("阀门信息不存在或已被禁用");
        if (!StringUtils.isNull(storageInfo.getOrderId())) {
            String updateOrderSql = "update weight_order set door_status = " + DoorStatusEnum.KX.getCode()
                    + " where code = '" + storageInfo.getOrderId() + "'";
            DataSourceInfo ds = dsDao.queryDSByOriginIdV1(storageInfoDto.getOrgId(), DataBaseEnum.MYSQL.getCode());
            if (ds != null) {
                JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
                jdbcTemplate.update(updateOrderSql);
            }
        }
        Date nowDate = new Date();
        storageInfo.setOrderId("");
        storageInfo.setRemark(storageInfoDto.getUpdator() + "复位操作");
        storageInfo.setUpdator(storageInfoDto.getUpdator());
        storageInfo.setOperationStatus(0);
        storageInfo.setDoorStatus(storageInfoDto.getDoorStatus());
        storageInfo.setUpdateTime(nowDate);
        Integer code = storageInfoDao.updateById(storageInfo);
        if (code > 0) {
            WeightStorageLog storageLog = new WeightStorageLog(storageInfo.getOrgId(),storageInfo.getOrgName(),
                    storageInfo.getStorageId(), storageInfo.getStorage(), null, storageInfoDto.getLogType());
            storageLog.setStatus(0);
            storageLog.setCreateTime(nowDate);
            storageLog.setUpdateTime(nowDate);
            storageLog.setCreator(storageInfo.getUpdator());
            storageLog.setRemark(storageInfo.getUpdator() + "复位操作");
            code = storageLogDao.insert(storageLog);
            if (code > 0)
                return RestResultDto.success("更新仓位状态成功");
        }
        throw new MessageCenterException("更新阀门状态异常~！");
    }

    /*
     * 查询操作的仓位信息
     * @return
     */
    @Cacheable(cacheNames = "storageInfo", key = "#orgId + '_' + #operationStatus")
    public List<WeightStorageInfo> findOperateStorage(Long orgId, Integer operationStatus) {
        QueryWrapper<WeightStorageInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0);
        if (!StringUtils.isNull(orgId))
            queryWrapper.eq("org_id", orgId);
        if (!StringUtils.isNull(operationStatus))
            queryWrapper.eq("operation_status", operationStatus);
        List<WeightStorageInfo> storageInfoList = storageInfoDao.selectList(queryWrapper);
        if (storageInfoList == null || storageInfoList.size() == 0)
            return null;
        System.out.println("调用数据库查询");
        return storageInfoList;
    }

    /**
     * 更新仓位信息
     * @param orgId
     * @param orgName
     * @param storageMap
     * @return
     */
    @CacheEvict(value = "storageInfo", allEntries = true)
    public RestResultDto updateStorageInfoAll(Long orgId, String orgName, Map<String, List<SysStorageVo>> storageMap) {
        if (StringUtils.isAllParamNull(orgId, orgName))
            throw new MessageCenterException("更新仓位信息参数错误");
        if (storageMap == null)
            throw new MessageCenterException("更新仓位库存信息错误");
        Date nowDate = new Date();
        if (storageMap.get("筒仓明细") != null) {
            List<SysStorageVo> storageVoList = storageMap.get("筒仓明细");
            for (SysStorageVo storageVo : storageVoList) {
                if (StringUtils.isNull(storageVo.getStorageId()) || StringUtils.isNull(storageVo.getType()))
                    continue;
//                if (orgId.longValue() != storageVo.getOrgId().longValue())
//                    continue;
                Integer storageType = storageVo.getType();
                if (storageType.intValue() != MaterialStoreTypeEnum.TC.getCode().intValue())
                    continue;
                WeightStorageInfo storageInfo = storageInfoDao.findByStorage(orgId, storageVo.getStorageId());
                if (storageInfo == null) {
                    storageInfo = new WeightStorageInfo(orgId, orgName, storageVo.getStorageId(), storageVo.getName(),
                            storageVo.getMaterialId(), storageVo.getMaterial(),
                            StringUtils.formatDouble(storageVo.getStoreValue() * 1000, 2), storageVo.getMaxCapacity(),
                            DoorStatusEnum.KX.getCode(), OperationStatusEnum.WCZ.getCode(), storageVo.getDeposit());
                    storageInfo.setCreator("系统同步");
                    storageInfo.setCreateTime(nowDate);
                    storageInfo.setUpdateTime(nowDate);
                    storageInfoDao.insert(storageInfo);
                } else {
                    storageInfo.setMaterial(storageVo.getNameNorms());
                    storageInfo.setMaterialId(storageVo.getMaterialId());
                    storageInfo.setStore(StringUtils.formatDouble(storageVo.getStoreValue() * 1000, 2));
                    storageInfo.setMaxStore(storageVo.getMaxCapacity());
                    storageInfo.setDeposit(storageVo.getDeposit());
                    storageInfoDao.updateById(storageInfo);
                }
            }
        }
        if (storageMap.get("共享仓明细") != null) {
            List<SysStorageVo> storageVoList = storageMap.get("共享仓明细");
            for (SysStorageVo storageVo : storageVoList) {
                if (StringUtils.isNull(storageVo.getStorageId()) || StringUtils.isNull(storageVo.getType()))
                    continue;
//                if (orgId.longValue() != storageVo.getOrgId().longValue())
//                    continue;
                Integer storageType = storageVo.getType();
                if (storageType.intValue() != MaterialStoreTypeEnum.TC.getCode().intValue())
                    continue;
                WeightStorageInfo storageInfo = storageInfoDao.findByStorage(orgId, storageVo.getStorageId());
                if (storageInfo == null) {
                    storageInfo = new WeightStorageInfo(orgId, orgName, storageVo.getStorageId(), storageVo.getName(),
                            storageVo.getMaterialId(), storageVo.getNameNorms(),
                            StringUtils.formatDouble(storageVo.getStoreValue() * 1000, 2), storageVo.getMaxCapacity(),
                            DoorStatusEnum.KX.getCode(), OperationStatusEnum.WCZ.getCode(), storageVo.getDeposit());
                    storageInfo.setCreator("系统同步");
                    storageInfo.setCreateTime(nowDate);
                    storageInfo.setUpdateTime(nowDate);
                    storageInfoDao.insert(storageInfo);
                } else {
                    storageInfo.setMaterial(storageVo.getNameNorms());
                    storageInfo.setMaterialId(storageVo.getMaterialId());
                    storageInfo.setStore(StringUtils.formatDouble(storageVo.getStoreValue() * 1000, 2));
                    storageInfo.setMaxStore(storageVo.getMaxCapacity());
                    storageInfo.setDeposit(storageVo.getDeposit());
                    storageInfoDao.updateById(storageInfo);
                }
            }
        }
        return RestResultDto.success("更新成功");
    }

    /**
     * 扫描二维码
     * @param storageInfoDto
     * @return
     */
    @CacheEvict(value = "storageInfo", allEntries = true)
    public RestResultDto scanOpenDoor(WeightStorageInfoDto storageInfoDto) {
        if (StringUtils.isAllParamNull(storageInfoDto.getOpenid(), storageInfoDto.getPhone(), storageInfoDto.getSecretCode()))
            throw new MessageCenterException("扫描仓位参数错误");
        String openid = storageInfoDto.getOpenid();//openid
        String phone = storageInfoDto.getPhone();//手机号
        String secretCode = storageInfoDto.getSecretCode();//二维码信息
        String encryptCode = AESCoder.decrypt(secretCode, Constant.storageSecret);
        if (StringUtils.isNull(encryptCode))
            throw new MessageCenterException("仓位二维码格式不正确");
        String[] storageText = encryptCode.split(",");
        if (storageText == null || storageText.length != 2)
            throw new MessageCenterException("二维码密文被篡改");
        Long orgId = StringUtils.convertLong(storageText[1]);
        Long storageId = StringUtils.convertLong(storageText[0]);
        if (StringUtils.isNull(orgId) || orgId.longValue() < 1)
            throw new MessageCenterException("二维码站点参数被篡改");
        if (StringUtils.isNull(storageId) || storageId.longValue() < 1)
            throw new MessageCenterException("二维码仓位参数被篡改");
        WeightOrder weightOrder = weightOrderDao.findByOrder(storageInfoDto.getOrderId(), openid,
                storageInfoDto.getCarNo(), phone);
        if (weightOrder == null)
            throw new MessageCenterException("未获取到您的订单信息");
        if (StringUtils.isNull(weightOrder.getOrgId()))
            throw new MessageCenterException("过磅订单站点错误");
        if (!StringUtils.isNull(weightOrder.getStorageType()) && weightOrder.getStorageType().intValue() != MaterialStoreTypeEnum.TC.getCode().intValue())
            throw new MessageCenterException("订单材料仓位类型错误");
        if (StringUtils.isNull(weightOrder.getStorageId()))
            throw new MessageCenterException("卸料订单未分配仓位信息");
        if (weightOrder.getStorageId() != storageId.longValue())
            throw new MessageCenterException("过磅订单仓位与二维码仓位不符");
        WeightStorageInfo storageInfo = storageInfoDao.findByStorage(weightOrder.getOrgId(), weightOrder.getStorageId());
        if (storageInfo == null || storageInfo.getStatus() == 1)
            throw new MessageCenterException("卸料仓位信息不存在");
        if (!StringUtils.isNull(storageInfo.getOrderId()) && !storageInfo.getOrderId().equals(storageInfoDto.getOrderId())) {
            String carNo = StringUtils.convertString(weightOrder.getBusNumber());
            if (!StringUtils.isNull(carNo))
                carNo = "(" + carNo + ")";
            throw new MessageCenterException(storageInfo.getStorage() + "卸料仓位已有其他车辆" + carNo + "占用,不支持同时操作");
        }
        Date nowDate = new Date();
        WeightStorageLog storageLog = new WeightStorageLog(orgId, weightOrder.getStation(), storageId, storageInfo.getStorage(),
                weightOrder.getCode(), StorageLogTypeEnum.JSYSM.getCode());
        storageLog.setStatus(0);
        storageLog.setCreateTime(nowDate);
        storageLog.setUpdateTime(nowDate);
        storageLog.setCreator(weightOrder.getDriver());
        Integer resultCode = storageLogDao.insert(storageLog);
        if (resultCode < 1)
            throw new MessageCenterException("更新仓位操作日志异常");
        Map<String, Object> map = new HashMap<>();
        map.put("info", storageInfo);
        map.put("order", weightOrder);
        return RestResultDto.success(map);
    }

    /**
     * 查询抄送未归位仓位
     * @param orgId
     * @return
     */
    public List<WeightStorageInfo> findTimeOut(Long orgId) {
        Date nowDate = new Date();
        if (StringUtils.isNull(orgId))
            throw new MessageCenterException("查询抄超时仓位参数错误");
        String time = DateUtil.convertString(DateUtil.convertBeforeMinDate(nowDate, 10));
        List<WeightStorageInfo> infoList = storageInfoDao.findTimeOut(orgId, time);
        if (infoList == null || infoList.size() == 0)
            throw new MessageCenterException("没有查询到超时数据");
        return infoList;
    }
    /**
     * 关闭阀门
     * @param storageInfoDto
     * @return
     */
    @CacheEvict(value = "storageInfo", allEntries = true)
    public RestResultDto operationDoor(WeightStorageInfoDto storageInfoDto) {
        if (storageInfoDto == null)
            throw new MessageCenterException("更新阀门参数为空");
        if (StringUtils.isNull(storageInfoDto.getStorageId()))
            throw new MessageCenterException("更新阀门ID参数为空");
        if (StringUtils.isNull(storageInfoDto.getOrgId()))
            throw new MessageCenterException("更新阀门站点ID参数为空");
        if (StringUtils.isNull(storageInfoDto.getDoorStatus()))
            throw new MessageCenterException("更新阀门状态参数为空");
//        if (!(storageInfoDto.getDoorStatus() == DoorStatusEnum.GB.getCode() || storageInfoDto.getDoorStatus() == DoorStatusEnum.KQ.getCode()))
//            throw new MessageCenterException("更新阀门状态参数为空");
        if (StringUtils.isNull(storageInfoDto.getLogType()))
            throw new MessageCenterException("阀门日志记录状态为空");
//        if (StringUtils.isNull(storageInfoDto.getDeposit()))
//            throw new MessageCenterException("阀门仓位寄存地址为空");
        WeightStorageInfo storageInfo = storageInfoDao.findByStorage(storageInfoDto.getOrgId(), storageInfoDto.getStorageId());
        Integer operateType = 0;
        if (!StringUtils.isNull(storageInfoDto.getOperateType()))
            operateType = storageInfoDto.getOperateType();
        if (operateType == 1) {
            if (!StringUtils.isNull(storageInfo.getOrderId())) {
                String updateOrderSql = "update weight_order set door_status = " + storageInfoDto.getDoorStatus()
                        + " where code = '" + storageInfo.getOrderId() + "'";
                DataSourceInfo ds = dsDao.queryDSByOriginIdV1(storageInfoDto.getOrgId(), DataBaseEnum.MYSQL.getCode());
                if (ds != null) {
                    JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
                    jdbcTemplate.update(updateOrderSql);
                }
            }
            storageInfo.setOrderId("");
            storageInfo.setRemark("系统复位操作");
        } else {
            if (storageInfoDto.getDoorStatus() == DoorStatusEnum.GB.getCode()) {
                if (storageInfoDto.getLogType() != StorageLogTypeEnum.XTGF.getCode())
                    throw new MessageCenterException("阀门状态与日志状态不匹配");
                storageInfo.setOrderId("");
            }
            if (storageInfoDto.getDoorStatus() == DoorStatusEnum.KQ.getCode()) {
                if (storageInfoDto.getLogType() != StorageLogTypeEnum.XTKF.getCode())
                    throw new MessageCenterException("阀门状态与日志状态不匹配");
            }
            if (storageInfo == null || storageInfo.getStatus().intValue() == 1)
                throw new MessageCenterException("阀门信息不存在或已被禁用");
            if (StringUtils.isNull(storageInfo.getOperationStatus()) && storageInfo.getOperationStatus().intValue() != OperationStatusEnum.GX.getCode())
                throw new MessageCenterException("阀门操作状态不匹配");
            WeightStorageLog lastLog = storageLogDao.findLastLog(storageInfoDto.getOrgId(), storageInfoDto.getStorageId());
            if (lastLog != null) {
                if (!StringUtils.isNull(lastLog.getType()) && !(lastLog.getType().intValue() == StorageLogTypeEnum.JSYKF.getCode()
                        || lastLog.getType().intValue() == StorageLogTypeEnum.JSYGF.getCode())) {
                    if (!StringUtils.isNull(storageInfo.getDoorStatus()) && storageInfo.getDoorStatus().intValue() == storageInfoDto.getDoorStatus().intValue())
                        throw new MessageCenterException("阀门状态与阀门更新状态一致,无需更新操作");
                }
            }
        }

//        if (!StringUtils.isNull(storageInfo.getDeposit()) && !storageInfo.getDeposit().equals(storageInfoDto.getDeposit()))
//            throw new MessageCenterException("阀门寄存地址与更新寄存地址不一致");
        Date nowDate = new Date();
        storageInfo.setOperationStatus(OperationStatusEnum.WCZ.getCode());
        storageInfo.setDoorStatus(storageInfoDto.getDoorStatus());
        storageInfo.setUpdateTime(nowDate);
        storageInfo.setUpdator("系统操作");
        Integer code = storageInfoDao.updateById(storageInfo);
        if (code > 0) {
            WeightStorageLog storageLog = new WeightStorageLog(storageInfo.getOrgId(),storageInfo.getOrgName(),
                    storageInfo.getStorageId(), storageInfo.getStorage(), null, storageInfoDto.getLogType());
            storageLog.setStatus(0);
            storageLog.setCreateTime(nowDate);
            storageLog.setUpdateTime(nowDate);
            storageLog.setCreator("系统操作");
            if (operateType == 1) {
                storageLog.setRemark("系统复位操作");
            }
            code = storageLogDao.insert(storageLog);
            if (code > 0)
                return RestResultDto.success("更新仓位状态成功");
        }
        throw new MessageCenterException("更新仓位状态操作异常");
    }

    /**
     * 驾驶员关闭阀门
     * @param storageInfoDto
     * @return
     */
    @CacheEvict(value = "storageInfo", allEntries = true)
    public RestResultDto driverOperationDoor(WeightStorageInfoDto storageInfoDto) {
        if (storageInfoDto == null)
            throw new MessageCenterException("更新阀门参数为空");
        if (StringUtils.isNull(storageInfoDto.getStorageId()))
            throw new MessageCenterException("更新阀门ID参数为空");
        if (StringUtils.isNull(storageInfoDto.getOrgId()))
            throw new MessageCenterException("更新阀门站点ID参数为空");
        if (StringUtils.isNull(storageInfoDto.getDoorStatus()))
            throw new MessageCenterException("更新阀门状态参数为空");
        if (!(storageInfoDto.getDoorStatus() == DoorStatusEnum.GB.getCode() || storageInfoDto.getDoorStatus() == DoorStatusEnum.KQ.getCode()))
            throw new MessageCenterException("阀门状态参数不匹配");
        if (StringUtils.isNull(storageInfoDto.getLogType()))
            throw new MessageCenterException("阀门日志记录状态为空");
        if (StringUtils.isNull(storageInfoDto.getOrderId()))
            throw new MessageCenterException("材料订单不存在");
        if (StringUtils.isNull(storageInfoDto.getCarNo()))
            throw new MessageCenterException("车牌信息不存在");
        String carNo = storageInfoDto.getCarNo().toUpperCase();
        Date nowDate = new Date();
        String beforeTime = DateUtil.convertString(DateUtil.convertBeforeDayDate(nowDate, 2));
        String orderSql = "select * from weight_order " +
                "where phone = '" + storageInfoDto.getPhone() + "' and openid = '" + storageInfoDto.getOpenid() + "' \n" +
                "and bus_number = '" + carNo + "' and storage_id = " + storageInfoDto.getStorageId() +
                " and gross > 0 and out_time is null and in_time > '" + beforeTime + "' order by id desc limit 1";
        DataSourceInfo ds = dsDao.queryDSByOriginIdV1(storageInfoDto.getOrgId(), DataBaseEnum.MYSQL.getCode());
        if (ds == null || ds.getType() != 0)
            throw new MessageCenterException("该工厂不支持扫码上料");
        JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
        List<WeightOrder> orderList = jdbcTemplate.query(orderSql, BeanPropertyRowMapper.newInstance(WeightOrder.class));
        if (orderList == null || orderList.size() == 0)
            throw new MessageCenterException("未获取到已过重磅的有效订单");
        String storageSql = "select * from sys_storage where status = 0 and id = " + storageInfoDto.getStorageId();
        List<SysStorage> storageList = jdbcTemplate.query(storageSql, BeanPropertyRowMapper.newInstance(SysStorage.class));
        if (orderList == null || orderList.size() == 0)
            throw new MessageCenterException("未获取到有效仓位信息");
        WeightStorageInfo storageInfo = storageInfoDao.findByStorage(storageInfoDto.getOrgId(), storageInfoDto.getStorageId());
        if (storageInfo == null || storageInfo.getStatus().intValue() == 1)
            throw new MessageCenterException("阀门信息不存在或已被禁用");
        if (StringUtils.isNull(storageInfo.getOperationStatus()) && storageInfo.getOperationStatus().intValue() != OperationStatusEnum.GX.getCode())
            throw new MessageCenterException("阀门操作状态不匹配");
        WeightStorageLog lastLog = storageLogDao.findLastLog(storageInfoDto.getOrgId(), storageInfoDto.getStorageId());
        if (lastLog != null) {
            if (!StringUtils.isNull(lastLog.getType()) && !(lastLog.getType().intValue() == StorageLogTypeEnum.XTGF.getCode()
                    || lastLog.getType().intValue() == StorageLogTypeEnum.XTKF.getCode())) {
                if (!StringUtils.isNull(storageInfo.getDoorStatus()) && storageInfo.getDoorStatus().intValue() == storageInfoDto.getDoorStatus().intValue())
                    throw new MessageCenterException("阀门状态与阀门更新状态一致,无需更新操作");
            }
        }
        String tip = "更新";
        WeightOrder weightOrder = orderList.get(0);//过磅单
        SysStorage sysStorage = storageList.get(0);//仓位信息
        String updateOrderSql = "";
        if (storageInfo.getDoorStatus() == DoorStatusEnum.KQ.getCode() || storageInfo.getDoorStatus() == DoorStatusEnum.SLZ.getCode()) {
            tip = "关闭" + storageInfo.getStorage() + "阀门成功,请等待阀门关闭~！";
            storageInfo.setOrderId("");
            if (storageInfoDto.getDoorStatus() != DoorStatusEnum.GB.getCode())
                throw new MessageCenterException("开启或上料中的仓位只能进行关闭操作");
        }
        if (storageInfo.getDoorStatus() == DoorStatusEnum.GB.getCode() || storageInfo.getDoorStatus() == DoorStatusEnum.KX.getCode()) {
            tip = "开启" + storageInfo.getStorage() + "阀门成功,请等待阀门开启~！";
            storageInfo.setOrderId(weightOrder.getCode());
            if (storageInfoDto.getDoorStatus() != DoorStatusEnum.KQ.getCode())
                throw new MessageCenterException("空闲或关闭的仓位只能进行开启操作");
        }
        if (StringUtils.isNull(weightOrder.getMaterialId()) || StringUtils.isNull(sysStorage.getMaterialId()))
            throw new MessageCenterException("过磅订单材料与仓位材料信息不一致");
        if (weightOrder.getMaterialId().longValue() != sysStorage.getMaterialId())
            throw new MessageCenterException("过磅订单材料与仓位材料信息不一致");

        updateOrderSql = "update weight_order set door_status = " + storageInfoDto.getDoorStatus()
                + " where code = '" + weightOrder.getCode() + "'";
        jdbcTemplate.update(updateOrderSql);
        weightOrder.setDoorStatus(storageInfoDto.getDoorStatus());
        weightOrderDao.updateById(weightOrder);//更新过磅订单仓位状态
        storageInfo.setOperationStatus(OperationStatusEnum.GX.getCode());
        storageInfo.setDoorStatus(storageInfoDto.getDoorStatus());
        storageInfo.setUpdateTime(nowDate);
        storageInfo.setUpdator(weightOrder.getDriver());
        Integer code = storageInfoDao.updateById(storageInfo);
        if (code > 0) {
            WeightStorageLog storageLog = new WeightStorageLog(storageInfo.getOrgId(),storageInfo.getOrgName(),
                    storageInfo.getStorageId(), storageInfo.getStorage(), weightOrder.getCode(), storageInfoDto.getLogType());
            storageLog.setStatus(0);
            storageLog.setCreateTime(nowDate);
            storageLog.setUpdateTime(nowDate);
            storageLog.setCreator(weightOrder.getDriver());
            code = storageLogDao.insert(storageLog);
            if (code > 0)
                return RestResultDto.success(tip, storageInfo);
        }
        throw new MessageCenterException("更新仓位状态操作异常");
    }
}